<?php

namespace app\admin\controller;

use app\common\BaseHelper as Helper;
use app\common\Common;

use app\admin\model\Productcategory;
use app\admin\model\Supplier;
use app\admin\model\Brand;
use app\admin\model\Image;
use app\admin\service\Product as ProductService;

use think\Db;
//use think\Cache;
use think\Exception;
use think\Request;

class Product extends Base
{

    public function _initialize()
    {
        parent::_initialize();

        $defaultWhere = $this->getDefaultWhere();
        $defaultWhere['status'] = ['neq', 0];
        $this->defaultWhere = $defaultWhere;
        $this->defaultOrder = 'status ASC, create_date DESC';

        // 商品分类
        $categorys = Productcategory::where([])->select();
        // 供货商
        $suppliers = Supplier::where(['status' => 1])->field('id, name')->select();
        $this->assign('categorys', $categorys);
        $this->assign('suppliers', $suppliers);

        if($this->request->action() == 'add' || $this->request->action() == 'edit'){
            // 单位
            $unitList = get_product_unit();
            // 快递运费 TODO
            // 商品品牌
            $brands = Brand::where([])->field('id, name')->select();

            $this->assign('unitList', $unitList);
            $this->assign('brands', $brands);
        }
    }

    public function index(){

        return parent::index();
    }

    /**
     * Add
     */
    public function add(Request $request){

        return parent::add($request);
    }

    /**
     * Edit
     */
    public function edit(Request $request){
        $model = model($this->model);
        $id = $request->param('id');
        // Get data info
        $info = $model->find($id);

        if(!$info){
            return $this->error('error !', 'admin/' . strtolower($this->model) . '/index');
        }
        // 销售方式
        $info['sales_way'] = explode(',', $info['sales_way']);
        // 详情图
        $detailImgs = Image::where(['related_id' => $info->id, 'tag' => 'detail_imgs'])->field('id, img_url')->order('sorting ASC')->select();
        $this->assign('detailImgs', $detailImgs);
        // 视频
        $videos = Image::where(['related_id' => $info->id, 'tag' => 'videos'])->field('id, img_url')->order('sorting ASC')->select();
        $this->assign('videos', $videos);

        return $this->view->fetch($this->editView, [
            'info' => $info
        ]);
    }

    /**
     * Save Post
     */
    public function savePost(Request $request){
        $model = model($this->model);

        if ($request->isPost()) {
            Db::startTrans();
            try {
                $data = $request->param();
                $data['price'] && $data['price'] = $data['price'] * 100;
                $data['purchase_price'] && $data['purchase_price'] = $data['purchase_price'] * 100;
                $data['wholesale_price'] && $data['wholesale_price'] = $data['wholesale_price'] * 100;
                $data['lowest_price'] && $data['lowest_price'] = $data['lowest_price'] * 100;
                // 调价前售价
                $data['old_price'] = $data['price'];
                // 调价前批发价
                $data['old_wholesale_price'] = $data['wholesale_price'];
                // 调价前会员积分
                $data['old_member_integral'] = $data['member_integral'];
                // 销售方式
                $data['sales_way'] = implode(',', $data['sales_way']);

                // 过期时间 TODO 采购时确定
                //$data['deadline'] = '';

                if (isset($data['id']) && $data['id']) {
                    // Update data
                    if($data['status'] == 2){
                        // 该商品是否已被使用
                        $usedInfo = $this->isUsed($data['id']);
                        if($usedInfo['code'] != 1){
                            return $this->error($usedInfo['msg']);
                        }
                    }
                    // 如果更换的封面图
                    if ($data['ori_img_url'] != $data['img_url']) {
                        // 跟换商品二维码
                        $data['qr_code'] = ProductService::createQrCode($data);
                        // 删除旧的商品二维码
                        @unlink(config('path.Upload_path'). $data['ori_qr_code']);
                    }

                    $result = $model->allowField(true)->save($data, ['id' => $data['id']]);
                    $logInfo = $this->admin->name . '更新了一条' . lang($this->model) . '数据。';
                    $afterAction = '_after_update';
                } else {
                    // Insert data
                    $barCode = $model->where(['bar_code' => $data['bar_code']])->value('bar_code');
                    if($barCode){
                        return $this->error('该条码已存在！');
                    }
                    $freshCode = $model->where(['fresh_code' => $data['fresh_code']])->value('fresh_code');
                    if($freshCode){
                        return $this->error('该生鲜码已存在！');
                    }
                    $pluCode = $model->where(['plu_code' => $data['plu_code']])->value('plu_code');
                    if($pluCode){
                        return $this->error('该PLU码已存在！');
                    }
                    $data['id'] = Helper::getUUID();
                    $data['create_date'] = date('Y-m-d H:i:s');
                    // 商品二维码
                    $data['qr_code'] = ProductService::createQrCode($data);

                    //初始化库存表(stock)
                    $Stock = new \app\admin\model\Stock();
                    $Stock->id = Helper::getUUID();
                    $Stock->product_id = $data['id'];
                    $Stock->save();

                    $result = $model->save($data);
                    $logInfo = $this->admin->name . '添加了一条' . lang($this->model) . '数据。';
                    $afterAction = '_after_insert';
                }

                if($result !== false) {
                    // 详情图
                    if(isset($data['detail_imgs']) && !empty($data['detail_imgs'])){
                        foreach ((array)$data['detail_imgs'] as $key => $detailImg) {
                            Image::where('img_url', $detailImg)->update(['related_id' => $data['id'], 'related_table' => 'product', 'tag' => 'detail_imgs', 'sorting' => $key]);
                        }
                    }
                    // 视频
                    if(isset($data['videos']) && !empty($data['videos'])){
                        foreach ((array)$data['videos'] as $videoKey => $video) {
                            Image::where('img_url', $video)->update(['related_id' => $data['id'], 'related_table' => 'product', 'tag' => 'videos', 'sorting' => $videoKey]);
                        }
                    }

                    // Query执行后的操作
                    $model->$afterAction($data);

                    // 写入日志
                    Common::adminLog($request, $logInfo);

                    Db::commit();
                    return $this->success('保存成功！', 'admin/' . strtolower($this->model) . '/index');
                } else {
                    Db::rollback();
                    return $this->error($model->getError());
                }
            } catch (Exception $e) {
                Db::rollback();
                return $this->error($e->getMessage());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * 启用/禁用
     */
    public function handle(Request $request){
        $model = model($this->model);

        if ($request->isPost()) {
            $data = $request->param();

            // 该商品是否已被使用
            $usedInfo = $this->isUsed($data['id']);
            if($usedInfo['code'] != 1){
                return $this->error($usedInfo['msg']);
            }

            $result = $model->allowField(true)->save($data, ['id' => $data['id']]);

            if($result !== false) {
                return $this->success('操作成功！', 'admin/' . strtolower($this->model) . '/index');
            } else {
                return $this->error($model->getError());
            }
        } else {
            return $this->error('提交方式错误！');
        }
    }

    /**
     * Delete
     */
    public function delete(){
        $request = $this->request;
        $id = $request->param('id');

        $model = model($this->model);
        $info = $model->find(['id', $id]);
        if(!$info){
            return redirect('admin/'.$this->model.'/index');
        }

        // 该商品是否已被使用
        $usedInfo = $this->isUsed($id);
        if($usedInfo['code'] != 1){
            return $this->error($usedInfo['msg']);
        }

        $result = $model->where('id', $id)->update(['status' => 0]);
        if ($result !== false) {
            // Query执行后的操作
            $model->_after_delete($id);

            $logInfo = $this->admin->name . '删除了1条' . lang($this->model) . '数据。';
            Common::adminLog($request, $logInfo);

            return $this->success('删除成功！', 'admin/' . strtolower($this->model) . '/index');
        } else {
            return $this->error('删除失败！', 'admin/' . strtolower($this->model) . '/index');
        }
    }

    /**
     * 处理列表数据
     */
    public function handleListData($data){
        foreach ($data as $item) {
            // 分类
            $item['category_id'] = Productcategory::where('id', $item['category_id'])->value('name');
            // 供货商
            $item['supplier_id'] = Supplier::where('id',  $item['supplier_id'])->value('name');
            // 单位
            $item['unit'] = show_product_unit($item['unit']);
        }

        return $data;
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if(isset($param['name']) && $param['name']){
            $where['name'] = ['like', '%'.$param['name'].'%'];
        }
        if(isset($param['category_id']) && $param['category_id']){
            $where['category_id'] = $param['category_id'];
        }
        if(isset($param['supplier_id']) && $param['supplier_id']){
            $where['supplier_id'] = $param['supplier_id'];
        }
        if(isset($param['price_type']) && $param['price_type']){
            $where['price_type'] = $param['price_type'];
        }

        return $where;
    }

    /**
     * 检查商品名称是否已存在
     */
    public function checkName(){
        $model = model($this->model);
        $name = $this->request->param('name');
        $info = $model->where(['name' => $name])->field('name')->find();

        if($info){
            return json(['status' => 1]);
        }else{
            return json(['status' => 0]);
        }
    }

    /**
     * 是否被使用过
     */
    protected function isUsed($id){
        if(!$id){
            return ['code' => 0, 'msg' => '参数错误'];
        }
        // 是否有使用该商品的优惠券
        $couponWhere = [
            'product_id' => $id,
        ];
        $coupon = \app\admin\model\CouponProduct::where($couponWhere)->find();
        if($coupon){
            return ['code' => 0, 'msg' => '有使用该商品的优惠券，请先删除优惠券'];
        }

        // 该商品是否在限时特价活动中
        $flashsaleWhere = [
            'product_id' => $id,
            'status' => ['neq', 0]
        ];
        $flashsale = \app\admin\model\Flashsale::where($flashsaleWhere)->find();
        if($flashsale){
            return ['code' => 0, 'msg' => '该商品已在限时特价活动中，请先去删除该活动'];
        }

        // 该商品是否在买赠活动中
        $buygiftsWhere = [
            'buy_product_id' => $id,
            'status' => ['neq', 0]
        ];
        $buygifts = \app\admin\model\Buygifts::where($buygiftsWhere)->find();
        if($buygifts){
            return ['code' => 0, 'msg' => '该商品已在买赠活动中，请先去删除该活动'];
        }

        // 该商品是否在加价换购活动中
        $repurchaseWhere = [
            'product_id' => $id,
            'status' => ['neq', 0]
        ];
        $repurchase = \app\admin\model\Repurchase::where($repurchaseWhere)->find();
        if($repurchase){
            return ['code' => 0, 'msg' => '该商品已在加价换购活动中，请先去删除该活动'];
        }

        return ['code' => 1, 'msg' => ''];
    }

    /**
     * 商品展示图片
     */
    public function getImgUrls(){
        $request = $this->request;
        $param = $request->param();

        if($request->isAjax()){
            $model = model('Image');

            $where = [];
            if (isset($param['id']) && $param['id']) {
                //$where['related_id'] = $param['id'];
            } elseif (isset($param['img_urls']) && $param['img_urls']) {
                $imgUrls = $param['img_urls'];
                $where['img_url'] = ['in', $imgUrls];
            } else {
                return json([
                    'code' => '0',
                    'msg' => '',
                    'data' => [],
                ]);
            }

            $order = 'created ASC';
            $data = $model->where($where)->order($order)->select();

            $result = [
                'code' => '0',
                'msg' => '',
                'data' => $data,
            ];

            return json($result);
        }

        return $this->view->fetch('product/img_urls', [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * 检测报告
     */
    public function getDetections(){
        $request = $this->request;
        $param = $request->param();

        if($request->isAjax()){
            $model = model('Image');

            $where = [];
            if (isset($param['id']) && $param['id']) {
                //$where['related_id'] = $param['id'];
            } elseif (isset($param['detections']) && $param['detections']) {
                //$ids = $param['detections'];
                $imgUrls = $param['detections'];
                $where['img_url'] = ['in', $imgUrls];
            } else {
                return json([
                    'code' => '0',
                    'msg' => '',
                    'data' => [],
                    'count' => 0,
                ]);
            }

            // 每页起始条数
            $start = ($param['page'] - 1) * $param['limit'];
            // 每页显示条数
            $length = $param['limit'];
            $order = 'created ASC';
            $data = $model->where($where)->order($order)->limit($start, $length)->select();
            $count = $model->where($where)->count();

            $result = [
                'code' => '0',
                'msg' => '',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return $this->view->fetch('product/detections', [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * 菜谱
     */
    public function getCookbooks(){
        $request = $this->request;
        $param = $request->param();

        if($request->isAjax()){
            $model = model('Cookbook');

            $where = [
                //'status' => 1
            ];
            if (isset($param['id']) && $param['id']) {
                $ids = model('Product')->where('id', $param['id'])->value('cookbook_ids');
                $where['id'] = ['in', $ids];
            } elseif (isset($param['cookbook_ids']) && $param['cookbook_ids']) {
                $ids = $param['cookbook_ids'];
                $where['id'] = ['in', $ids];
            } else {
                return json([
                    'code' => '0',
                    'msg' => '',
                    'data' => [],
                    'count' => 0,
                ]);
            }
            if(isset($param['name']) && $param['name']){
                $where['name'] = ['like', '%'.$param['name'].'%'];
            }
            $order = 'create_date DESC';
            $data = $model->where($where)->order($order)->select();
            $count = $model->where($where)->count();

            $result = [
                'code' => '0',
                'msg' => '',
                'data' => $data,
                'count' => $count,
            ];

            return json($result);
        }

        return $this->view->fetch('product/cookbooks', [
            'pageSize' => ['url' => fullUrl($request->path())],
            'searchFields' => $this->searchFields,
            'param' => $request->param()
        ]);
    }

    /**
     * 生成条码 （13位数）
     */
    public function cerateBarcode(){
        $recursive = function () use (&$recursive) {
            $data = rand_string(13, 1);

            $model = model($this->model);
            $exist = $model->where(['bar_code' => $data])->value('bar_code');
            if ($exist) {
                $data = $recursive();
            }
            return $data;
        };

        return $this->success('成功','', $recursive());
    }

    /**
     * 生成生鲜码 （5位数）
     */
    public function cerateFreshcode(){
        $recursive = function () use (&$recursive) {
            $data = rand_string(5, 1);

            $model = model($this->model);
            $exist = $model->where(['fresh_code' => $data])->value('fresh_code');
            if ($exist) {
                $data = $recursive();
            }
            return $data;
        };

        return $this->success('成功','', $recursive());
    }

    /**
     * 生成PLU码 称重用（0-4000）
     */
    public function ceratePlucode(){
        $recursive = function () use (&$recursive) {
            $data = mt_rand(0, 3) . rand_string(3, 1);

            $model = model($this->model);
            $exist = $model->where(['plu_code' => $data])->value('plu_code');
            if ($exist) {
                $data = $recursive();
            }
            return $data;
        };

        return $this->success('成功','', $recursive());
    }

    /**
     * 导出数据
     */
    public function export(){
        $result = ProductService::export($this->request);
        if($result['code'] == 2){
            $this->error($result['msg'], url('admin/product/index'));
        }

        return redirect('admin/product/index');
    }

}